# event of fsm
from Shell.fsm.EventDefine import event_NETWORKGAME_GAMESTART, event_NETWORKGAME_BACKTOMAINMENU
# event listener
from direct.showbase import DirectObject
# event driven
from Cube.map import event_QMEMBERLISTMGR_MEMBERMOVE, event_QMEMBERLISTMGR_MEMBERLEAVE
from Cube.command.QCmdInputPipe.EventDefine import event_CMDPIPE_SERVERLEAVE
from Cube.command.QCommand.EventDefine import event_QCMD_STARTGAMEBTNON
# reverse of MemberType string
from Cube.map import QMemberType
from Shell.data.UIString import uiString
# cmd
from Cube.command.QCommand import QCmdChatMessage, QCmdMemberMove, QCmdMemberLeave, QCmdStartGameBtnOn
# animation
from direct.interval.IntervalGlobal import *
# MapBody, MapBodyController
from Cube.map import MapBodyControllerReset, MapMgrGet

class GameLobbyController(DirectObject.DirectObject):
    def __init__(self,
                 model,
                 view):

        self.model = model
        self.view = view
        self.ActionEnable = True
        self.MemberMoveDone = True
        self.RevMemberTypeMapping = {uiString[QMemberType.COMPUTER]:QMemberType.COMPUTER,
                                     uiString[QMemberType.OPEN]:QMemberType.OPEN,
                                     uiString[QMemberType.CLOSE]:QMemberType.CLOSE,
                                     }
        self.ChatMessageSend = QCmdChatMessage().Send
        self.MemberMoveSend = QCmdMemberMove().Send

        self.view.ControllerSet(self)

        self.accept(event_QMEMBERLISTMGR_MEMBERMOVE, self.MemberMoveDoneSet)

        # client only
        if not self.model.IsServerMode():
            self.accept(event_QMEMBERLISTMGR_MEMBERLEAVE, self.ClientKickedHandle)
            self.accept(event_CMDPIPE_SERVERLEAVE, self.ServerLeaveHandle)
            self.accept(event_QCMD_STARTGAMEBTNON, self.StartGameBtnOnHandle)

    def MemberMoveHandle(self, teamID):
        if self.ActionEnable:
            self.MemberMoveSend(teamID)
            self.ActionEnable = False

    def MemberMoveDoneSet(self, *args):
        self.ActionEnable = True

    def ChatStringHandle(self, text):
        if text and self.ActionEnable:
            self.ChatMessageSend(text)

    # server only
    def StartGameHandle(self):
        if self.ActionEnable:
            self.ActionEnable = False
            QCmdStartGameBtnOn().Send()
            MapBodyControllerReset("server") # setup MapBodyController before game start
            self._StartGameCountDownHandle()

    # client only
    def StartGameBtnOnHandle(self):
        self.ActionEnable = False
        MapBodyControllerReset("client") # setup MapBodyController before game start
        self._StartGameCountDownHandle()

    def QuitGameLobbyHandle(self):
        if self.ActionEnable:
            messenger.send(event_NETWORKGAME_BACKTOMAINMENU)

    # server only
    def MemberAssignHandle(self, arg, memberID):
        memberType = self.RevMemberTypeMapping.get(arg, QMemberType.HUMAN)
        self.model.MemberAssignHandle(memberID, memberType)

    # client only
    def ClientKickedHandle(self, memberID, memberName):
        if self.model.MyMemberIDGet() == memberID:
            self.ActionEnable = False
            self.view.MessageDisplay(uiString[r'Oops! I has been kicked'],
                                     fn = self._DestroyMsgBoxAndLeaveGameLobby)
    # client only
    def ServerLeaveHandle(self):
        self.ActionEnable = False
        self.view.MessageDisplay(uiString["Server has leaved"],
                                 fn = self._DestroyMsgBoxAndLeaveGameLobby)

    def _DestroyMsgBoxAndLeaveGameLobby(self, value):
        self.ActionEnable = True
        self.view.MessageDisplayDialogDestroy()
        self.QuitGameLobbyHandle()

    def _StartGameCountDownHandle(self):
        printText = uiString["Start the game after 3 sec..."]
        self.view.ChatRoom.appendMessage(printText)
        animation = Sequence()
        for i in xrange(3,0,-1):
            printText = "%d..."%(i)
            animation.append(Func(self.view.ChatRoom.appendMessage, printText))
            animation.append(Wait(1.0))
        animation.append(Func(messenger.send, event_NETWORKGAME_GAMESTART))
        animation.start()

# host ip display ---------------------------------------------------
    def HostIPDisplayHandle(self):
        if self.ActionEnable:
            self.ActionEnable = False
            ipAddress = self.model.IPAddressGet()
            self.view.HostIPDisplayHandle(text = "IP: %s"%(ipAddress))

    def HostIPDisplayDialogDestroy(self, value):
        self.view.HostIPDisplayDialogDestroy()
        self.ActionEnable = True

# destroy -----------------------------------------------------------
    def destroy(self):
        self.ignoreAll()
